import { injectable } from "inversify";
import jsonwebtoken from "jsonwebtoken";
import passport from "passport";
import { ExtractJwt, Strategy } from "passport-jwt";

@injectable()
export class JWT {
  constructor() {
    this.strategy();
  }

  // 定义jwt盐
  private secret: string = "songzx$%&*()_+";

  private jwtOptions = {
    jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
    secretOrKey: this.secret,
  };

  // 中间件
  static middleware() {
    // 让请求经过jwt验证
    return passport.authenticate("jwt", { session: false });
  }

  // 定义策略
  public strategy() {
    const strategy = new Strategy(this.jwtOptions, (payload, done) => {
      done(null, payload);
    });
    passport.use(strategy);
  }

  // 生成jwt,payload为用户信息,过期时间为7天
  public createToken(payload: any) {
    return jsonwebtoken.sign(payload, this.secret, { expiresIn: "7d" });
  }

  // 初始化
  public init() {
    return passport.initialize();
  }
}
